package com.steven.ourcontest.information.view

import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.daimajia.numberprogressbar.NumberProgressBar
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.base.DialogBuilder
import com.steven.ourcontest.information.viewmodel.UploadViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.FileRequestBody
import com.steven.ourcontest.net.RetrofitCallback
import com.steven.ourcontest.utils.Identity
import com.steven.ourcontest.utils.openAlbum
import com.steven.ourcontest.utils.toast
import id.zelory.compressor.Compressor
import kotlinx.android.synthetic.main.activity_upload_student_image.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class UploadImageActivity : BaseActivity() {
    private val uploadViewModel: UploadViewModel by viewModels()
    var capturPath: String = ""
    private var identity: Identity? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getViewId(): Int? {
        return R.layout.activity_upload_student_image
    }

    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun initView() {
        identity = intent.getSerializableExtra("identity") as? Identity?
        if (identity == null) {
            finish()
            return
        }
        when(identity){
            Identity.TEACHER->{
                tv_title?.text = "上传相关证明材料"
                iv_upload?.setImageResource(R.drawable.bg_custom_identity_upload)
            }
            Identity.STUDENT->{
            }
        }
        iv_upload?.setOnClickListener {
            openAlbum(this)
        }
        tv_confirm?.setOnClickListener {
            if (LoginController.isLogin && LoginController.userId != 0L) {
                if (capturPath != "") {
                    val file = File(capturPath)
                    val dialog = DialogBuilder(this)
                        .setCancelable(false)
                        .build(R.layout.dialog_upload)
                    dialog.show()
                    val progressView = dialog.findViewById<NumberProgressBar>(R.id.progress)
                    GlobalScope.launch(Dispatchers.Default) {
                        val resFile = Compressor.compress(this@UploadImageActivity, file)
                        val fileRQ =
                            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), resFile)
                        val realBody =
                            FileRequestBody(fileRQ, object : RetrofitCallback<EmptyResponse>() {
                                override fun onLoading(total: Long, progress: Long) {
                                    super.onLoading(total, progress)
                                    GlobalScope.launch(Dispatchers.Main) {
                                        progressView.progress =
                                            ((progress / total.toFloat()) * 100).toInt()
                                        if (total == progress) {
                                            dialog.dismiss()
                                        }
                                    }
                                }
                            })
                        val body: RequestBody = MultipartBody.Builder()
                            .addFormDataPart("image", resFile.name, realBody)
                            .build()
                        uploadViewModel.uploadImage(body)
                    }
                }
            }
        }
        uploadViewModel.uploadRes.observe(this, Observer {
            if (it?.msg == "success") {
                AppRouter.startIdentifyActivity(this, identity!!)
                finish()
            } else {
                toast(it?.msg.toString())
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                val cursor: Cursor? = data?.data?.let {
                    contentResolver.query(
                        it,
                        arrayOf(MediaStore.Images.Media.DATA),
                        null,
                        null,
                        null
                    )
                }
                cursor?.moveToFirst()
                capturPath = cursor?.getString(
                    cursor.getColumnIndex(
                        MediaStore.Images.Media.DATA
                    )
                ) ?: ""
                cursor?.close()
                try {
                    if (capturPath == "") {
                        throw Exception("file path is error")
                    }
                    val fis = File(capturPath)
                    iv_upload?.setImageURI(Uri.fromFile(fis))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 2) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    val intent =
                        Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                    startActivityForResult(intent, 1)
                } else {
                    toast("缺少读取权限！")
                }
            }
        }
    }
}